<template>
  <div class="component-container">
    <div class="component-title-wrapper">
      <div class="component-title">
        <span class="title-breadcrumb">用户运营</span>
      </div>
    </div>
    <div class="component-body-wrapper">
      <div class="component-body">
        <section>
          <div class="component-title">
            <span><span class="title-breadcrumb">用户概览</span></span>
          </div>
          <div class="statistics">
            <div class="statistics-item"><div>注册用户总数</div><div class="item-count" v-loading="loadingUserCount">{{userCount}}</div></div>
          </div>
        </section>
        <section>
          <div class="component-title">
            <span><span class="title-breadcrumb">用户列表</span></span>
          </div>
          <div class="search-bar">
            <span>
              <el-input v-model="searchData.email" placeholder="请输入用户邮箱" clearable style="width: 220px"></el-input>
            </span>
            <div class="date-wrapper">
              <el-col :span="11">
                <el-date-picker type="date" placeholder="请选择创建起始日期" v-model="searchData.start" value-format="timestamp" :clearable="false" style="width: 100%;"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2">-</el-col>
              <el-col :span="11">
                <el-date-picker placeholder="请选择创建截止日期" v-model="searchData.end" value-format="timestamp" :clearable="false" style="width: 100%;"></el-date-picker>
              </el-col>
            </div>
            <span>
              <el-select v-model="searchData.loginType" placeholder="请输入登录类型">
                <el-option value="" label="全部"></el-option>
                <el-option value="app"></el-option>
                <el-option value="google"></el-option>
                <el-option value="alexa"></el-option>
              </el-select>
            </span>
            <span>
              <el-button plain @click="getUserList(true)">搜索</el-button>
            </span>
          </div>
          <div>
            <el-table :data="userList" style="width: 100%" border v-loading="loadingUserList">
              <el-table-column label="邮箱" prop="email" min-width="250"></el-table-column>
              <el-table-column label="创建时间" prop="created_at" min-width="200"></el-table-column>
              <el-table-column label="最后登录时间" prop="updated_at" min-width="200"></el-table-column>
              <el-table-column prop="login_type_standard" label="登录方式" min-width="150"></el-table-column>
              <el-table-column label="操作" min-width="120">
                <template slot-scope="scope">
                  <el-button type="text" @click="showUserDetail(scope.row)">查看</el-button>
                  <el-button type="text" @click="editUser(scope.row)" v-if="isManager">改密</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div style="padding: 20px 0; text-align: right;">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageConfig.pageIndex"
                :page-sizes="[10, 15, 20]"
                :page-size="pageConfig.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pageConfig.totalCount">
              </el-pagination>
            </div>
          </div>
        </section>
      </div>
    </div>
    <el-dialog
      title="重置密码"
      :visible.sync="editDialogVisible"
      width="500px">
      <div class="content-wrapper">
        <el-form ref="resetForm" :model="resetForm" :rules="rules" class="reset-form">
          <div class="title mb20">请重设您的账号密码</div>
          <el-form-item prop="newPwd">
            <el-input placeholder="请输入新密码" v-model="resetForm.newPwd" show-password></el-input>
          </el-form-item>
          <el-form-item prop="newPwdRepeat">
            <el-input placeholder="请输入确认密码" v-model="resetForm.newPwdRepeat" show-password></el-input>
          </el-form-item>
          <div class="tip mb20">密码长度6-18位</div>
          <div class="mb20"><el-button type="primary" style="width: 100%;" @click="submitResetForm">提交</el-button></div>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from "@/utils/formUtil";
export default {
  data () {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.resetForm.newPwd) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    return {
      userList: [],
      pageConfig: {
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0,
        totalPage: 0
      },
      searchData: {
        start: '',
        end: '',
        loginType: '',
        email: '',
      },
      editDialogVisible: false,
      resetForm: {
        id: '',
        newPwd: '',
        newPwdRepeat: '',
      },
      rules: {
        newPwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度应为6-18位', trigger: 'blur' }
        ],
        newPwdRepeat: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度应为6-18位', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
      },
      userCount: 0,
      loadingUserCount: true,
      loadingUserList: true,
    };
  },
  computed: {
    isManager() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1311210362356432897')
    },
  },
  mixins: [dingMixin],
  activated() {
    if(window.NEEDREFRESH) {
      formUtil.resetData(this.searchData);
      this.getSearchTime()
      this.getUserList(true)
      window.NEEDREFRESH = false;
    }
  },
  async mounted () {
    this.getSearchTime()
    this.getUserCount()
    this.getUserList(true)
  },
  methods: {
    //获取查询起始日期时间戳
    getSearchTime() {
      let date = new Date();
      let year = date.getFullYear();
      let mouth = date.getMonth() + 1;
      let day = date.getDate();
      let today = year + '-' + mouth + '-' + day;
      let lastYearToday = (year-1) + '-' + mouth + '-' + day;
      this.searchData.start = new Date(lastYearToday).getTime();
      this.searchData.end = new Date(today).getTime();
    },
    //获取用户总数
    async getUserCount() {
      this.loadingUserCount = true;
      let { data: res } = await this.$http.post( "bms/user/count" );
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      this.userCount = res.data;
      this.loadingUserCount = false;
    },
    async getUserList(init) {
      this.loadingUserList = true;
      if(init) this.pageConfig.pageIndex = 1;
      if(!this.searchData.start) return this.$message.error('请选择创建起始日期')
      if(!this.searchData.end) return this.$message.error('请选择创建起始日期')
      if (this.searchData.start > this.searchData.end) return this.$message.error("起始日期应小于或等于截止日期")
      let {data: res} = await this.$http.post('bms/user/list?pageNum='+this.pageConfig.pageIndex+'&pageSize='+this.pageConfig.pageSize
      +'&start='+this.searchData.start+'&end='+(this.searchData.end + 24*60*60*1000-1)+'&timezoneOffset=28800', {
        orderBy: {
          col: 'updated_at',
          type: 'desc'
        },
        loginType: this.searchData.loginType,
        email: this.searchData.email,
      })
      if (res.resultCode !== "000") return this.$message.error(res.resultMessage);
      res.data.list.forEach( item => {
        if(item.login_type && item.login_type.length > 13) {
          item.login_type_standard = item.login_type.substring(0, item.login_type.length-13).replace("-", "")
        } else if(item.login_type && item.login_type.length <= 13) {
          item.login_type_standard = item.login_type
        } else {
          item.login_type_standard = '-'
        }
      })
      this.userList = res.data.list
      this.loadingUserList = false;
      if(init) {
        this.pageConfig.totalPage = res.data.pages;
        this.pageConfig.totalCount = Number(res.data.total);
      }
    },
    handleSizeChange(val) {
      this.pageConfig.pageSize = val;
      this.getUserList(true);
    },
    handleCurrentChange(val) {
      this.pageConfig.pageIndex = val;
      this.getUserList();
    },
    showUserDetail(data) {
      this.$router.push({name: 'bms-userDetail', query: { userInfo: JSON.stringify(data) }});
    },
    editUser(row) {
      if(this.$refs.resetForm) this.$refs.resetForm.clearValidate();
      formUtil.resetData(this.resetForm);
      this.resetForm.id = row.id;
      this.editDialogVisible = true;
    },
    submitResetForm() {
      this.$refs.resetForm.validate(async (valid) => {
        if (valid) {
          let {data: res} = await this.$http.post('bms/user/reset/password', this.resetForm)
          if(res.resultCode !== '000') return this.$message.error(res.resultMessage)
          this.$message.success('修改成功');
          this.editDialogVisible = false;
        } else {
          return false;
        }
      });
    }
  }
}
</script>

<style lang='scss' scoped>
.component-container {
  min-width: 1000px;
  padding-bottom: 40px;
  .component-title-wrapper {
    font-size: 12px;
    color: rgb(102, 102, 102);
    height: 64px;
    line-height: 64px;
    padding: 0 16px;
    .component-title {
      border-bottom: 1px solid #ecedee;
      .title-breadcrumb {
        font-weight: bolder;
        font-size: 16px;
        padding: 0 10px;
        font-weight: bolder;
        display: inline-block;
        position: relative;
        &::before {
          position: absolute;
          content: "";
          left: 0;
          top: 50%;
          width: 4px;
          height: 20px;
          margin-top: -10px;
          background: #0070cc;
        }
      }
    }
  }
  .component-body-wrapper {
    .component-body {
      padding: 0 16px;
      .component-title {
        font-size: 12px;
        color: rgb(102, 102, 102);
        padding: 20px 0;
        position: relative;
        .title-breadcrumb {
          font-weight: bolder;
          font-size: 16px;
          padding: 0 10px;
          font-weight: bolder;
          display: inline-block;
          position: relative;
          &::before {
            position: absolute;
            content: "";
            left: 0;
            top: 50%;
            width: 4px;
            height: 20px;
            margin-top: -10px;
            background: #bac8cf;
          }
        }
        .condition-right {
          position: absolute;
          right: 0;
          top: 10px;
        }
      }
      .statistics {
        border: 1px solid #ecedee;
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;
        .statistics-item {
          padding: 20px 28px;
          border-right: 1px solid #ecedee;
          flex: 1;
          &:last-child {
            border: none;
          }
          .item-count {
            font-weight: 400;
            font-size: 28px;
            line-height: 40px;
            color: #333333;
          }
        }
      }
      .search-bar {
        display: flex;
        margin: 20px 0 16px;
        > span {
          margin-right: 12px;
        }
        .date-wrapper {
          margin-right: 20px;
          width: 480px;
          text-align: center;
          line-height: 36px;
        }
      }
    }
  }
}
.el-dialog {
  .content-wrapper {
    margin: -30px -20px;
    border-top: 1px solid #DCDFE6;
    min-height: 320px;
    overflow: auto;
    .reset-form {
      padding: 30px 40px;
      max-width: 300px;
      margin: 0 auto;
      .title {
        font-weight: 700;
      }
      .tip {
        font-size: 12px;
        margin-top: 5px;
      }
      .mb20 {
        margin-bottom: 20px;
      }
    }
    .form-wrapper {
      z-index: 1;
    }
  }
}
</style>